package com.arunsawad.ilertu.activity;

import java.io.StringReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;

import com.arunsawad.ilertu.R;
import com.arunsawad.ilertu.common.AsyncActivity;
import com.arunsawad.ilertu.common.Constants;
import com.arunsawad.ilertu.common.RequestTask;
import com.arunsawad.ilertu.common.Utils;

public class SignIn extends Activity implements AsyncActivity {
	SharedPreferences preferences;
	Button btnSignIn;
	EditText txtUsername;
	EditText txtPassword;
	ProgressDialog bar;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.act_signin);
		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,
				R.layout.title0_imgbtn_txt);
		
		initTitle();
		
		preferences = getSharedPreferences(Constants.PREF_FILE, MODE_PRIVATE);

		// validation
		String username = preferences.getString(Constants.PREF_USER_NAME, "");
		if (!username.equals("")) {
			Intent intent = new Intent(this, Home.class);
			startActivity(intent);
		}
	}

	public void initTitle() {
		ImageButton imgBtn1 = (ImageButton) findViewById(R.id.title0_imgBtn1);
		imgBtn1.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(getApplicationContext(), Home.class);
				startActivity(intent);
			}
		});

		TextView txtTitle = (TextView) findViewById(R.id.title0_txtTitle);
		txtTitle.setText(getString(R.string.sign_in));
	}
	
	// {{ onClick events
	public void signIn(View view) {
		bar = new ProgressDialog(SignIn.this);
		bar.setIndeterminate(true);
		bar.show();

		// disable Sign In button
		btnSignIn = (Button) findViewById(R.id.signin_btnSignIn);
		btnSignIn.setClickable(false);

		txtUsername = (EditText) findViewById(R.id.signin_txtUsername);
		txtPassword = (EditText) findViewById(R.id.signin_txtPassword);
		String msg = String.format(Constants.MSG, "ilertu.user-sign-in",
				txtUsername.getText(), txtPassword.getText(),
				preferences.getString(Constants.PREF_LANGUAGE, "en"), "");

		RequestTask task = new RequestTask();
		task.setListener(this);
		task.execute(Constants.URL_SIGN_IN, msg);
	}

	public void forgotPassword(View view) {
		Intent intent = new Intent(this, ForgotPassword.class);
		startActivity(intent);
	}

	public void joinNow(View view) {
		Intent intent = new Intent(this, SignUp.class);
		startActivity(intent);
	}

	// }}

	// {{ callback
	@Override
	public void onRequestCompleted(String results) {
		if (results != null) {
			DocumentBuilderFactory factory = DocumentBuilderFactory
					.newInstance();
			DocumentBuilder builder;
			try {
				builder = factory.newDocumentBuilder();
				Document document = builder.parse(new InputSource(
						new StringReader(results)));

				NodeList listOfItems = document.getElementsByTagName("user");
				int totalElements = listOfItems.getLength();

				if (totalElements > 0) {
					Element user = (Element) listOfItems.item(0);

					String userId = user.getAttribute("id");
					String password = user.getElementsByTagName("password")
							.item(0).getTextContent();
					String username = user.getElementsByTagName("username")
							.item(0).getTextContent();

					SharedPreferences.Editor editor = getSharedPreferences(
							Constants.PREF_FILE, MODE_PRIVATE).edit();
					editor.putString(Constants.PREF_USER_ID, userId);
					editor.putString(Constants.PREF_USER_NAME, username);
					editor.putString(Constants.PREF_PASSWORD, password);
					editor.commit();

					Intent myIntent = new Intent(this, Home.class);
					startActivity(myIntent);
				} else {
					Utils.alert(SignIn.this, getString(R.string.sign_in_failed));
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		btnSignIn = (Button) findViewById(R.id.signin_btnSignIn);
		btnSignIn.setClickable(true);
		bar.hide();
	}
	// }}
}
